package leetcode.Y2024M5D27;

import org.junit.Test;

public class S19 {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        // 准备双节点a，b，ab相距n-1，将a，b同时移动，直到b在最末尾上，此时a就在倒数第n个节点上
        ListNode res = new ListNode(-1);
        res.next = head;
        ListNode left = res;
        ListNode right = head;
        for (int i = 1; i < n; i++) {
            right = right.next;
        }
        while (right.next!=null) {
            right = right.next;
            left = left.next;
        }
        ListNode del = left.next;
        left.next = del.next;
        return res.next;


    }

    @Test
    public void test() {
        int[] head = {1, 2, 3, 4, 5};
        int n = 2;
        ListNode listNode = ListNode.createListNode(head);
        removeNthFromEnd(listNode,n);
    }

    @Test
    public void test1() {
        int[] head = {1};
        int n = 1;
        ListNode listNode = ListNode.createListNode(head);
        removeNthFromEnd(listNode,n);
    }
    @Test
    public void test2() {
        int[] head = {1,2};
        int n = 1;
        ListNode listNode = ListNode.createListNode(head);
        removeNthFromEnd(listNode,n);
    }
}
